package com.titleevaluation.controller;

import com.titleevaluation.dto.LoginRequest;
import com.titleevaluation.dto.LoginResponse;
import com.titleevaluation.entity.User;
import com.titleevaluation.service.AuthService;
import com.titleevaluation.repository.RoleRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;
    private final RoleRepository roleRepository;

    public AuthController(AuthService authService, RoleRepository roleRepository) {
        this.authService = authService;
        this.roleRepository = roleRepository;
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody User user) {
        // 默认注册为客户角色
        roleRepository.findByRoleName("客户").ifPresent(user::setRole);
        User registeredUser = authService.registerUser(user);
        return ResponseEntity.ok("User registered successfully!");
    }

    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        String jwt = authService.loginUser(loginRequest.getUsername(), loginRequest.getPassword());
        UserDetails userDetails = authService.loadUserByUsername(loginRequest.getUsername());
        String roleName = ((User) userDetails).getRole().getRoleName();
        return ResponseEntity.ok(new LoginResponse(jwt, userDetails.getUsername(), roleName));
    }
}

